package com.haredot.controller;

import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.haredot.entity.Order;
import com.haredot.entity.enums.OrderStatus;
import com.haredot.holder.TokenContextHolder;
import com.haredot.service.OrderService;
import com.haredot.vo.OrderVo;
import com.haredot.vo.R;
import org.springframework.beans.BeanUtils;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import java.time.Duration;
import java.time.LocalDateTime;
import java.time.temporal.ChronoUnit;
import java.util.List;
import java.util.Map;

@RestController
@RequestMapping("/order")
public class OrderController {

    @Resource
    private OrderService orderService;

    @GetMapping("/list")
    public R<?> orderList(@RequestParam(value = "page", required = false, defaultValue = "1") Long page,
                          @RequestParam(value = "rows", required = false, defaultValue = "10") Long rows) {
        Page<Order> pageVo = new Page<>(page, rows);
        Long userId = TokenContextHolder.getCurrentUserId();
        orderService.queryOrderList(pageVo, userId);
        // 获取 每页的数据、并返回
        List<OrderVo> list = pageVo.getRecords().stream().map(order -> {
            OrderVo orderVo = new OrderVo();
            BeanUtils.copyProperties(order, orderVo);
            // 如果订单是 待支付状态，则 显示剩余的存活时间
            if (order.getState() == OrderStatus.WAIT_BUYER_PAY) {
                // 获取下单时间 ， 并计算 还剩余多久时间 ，30分钟
                // 公式： 30分钟 + 下单时间 - 当前系统时间
                long until = LocalDateTime.now().until(order.getCreateTime().plus(Duration.ofMinutes(30)), ChronoUnit.SECONDS);
                orderVo.setLifeTime(until);
            }
            return orderVo;
        }).toList();
        Map<String, Object> map = Map.of("total", pageVo.getTotal(), "list", list);
        return R.ok().data(map);
    }

    @DeleteMapping("/{orderId}")
    public R<?> cancelOrder(@PathVariable("orderId") Long orderId) {
        LambdaUpdateWrapper<Order> orderLambdaUpdateWrapper = new LambdaUpdateWrapper<Order>()
                .set(Order::getState, OrderStatus.TRADE_CLOSED)
                .eq(Order::getId, orderId);
        boolean ret = orderService.update(null, orderLambdaUpdateWrapper);

        return ret ? R.ok().build() : R.fail().build();
    }
}
